package com.zn;


import com.zn.api.Servlet;
import com.zn.entity.Request;
import com.zn.entity.Response;
import com.zn.handler.DispatcherHandler;
import com.zn.handler.RequestHandler;
import com.zn.handler.ServletHandler;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Description:启动类
 * @Author: zhangnan
 * @Date: 2019/11/23
 */
public class BootStrap {

    public static void main(String[] args) throws IOException, InterruptedException {

        System.out.println("正在加载容器...");
        ServletHandler.loadAllServlets();

        //监听8888端口
        ServerSocket socket = new ServerSocket();
        socket.bind(new InetSocketAddress(8888));
        System.out.println("8888端口已监听...");

        while (true) {
            Socket accept = socket.accept();
            //封装请求,请求过来就是个字符串，用截串等方法把它包装一下方便我们使用
            Request request = new RequestHandler().requestHandler(accept);
            System.out.println("接受到请求...");
            System.out.println(request);

            //使用分发器去解析一下请求，看看该请求对应哪个servlet去处理
            Servlet servlet = DispatcherHandler.matchServlet(request);
            Response response = new Response();
            //让servlet去处理强求，获取相应的字符串
            String res = servlet.service(request, response);

            //将构建的响应返回给浏览区，让浏览器去渲染
            OutputStream outputStream = accept.getOutputStream();
            outputStream.write(res.getBytes());
            outputStream.flush();
            outputStream.close();
        }
    }
}
